package com.banshuibao.bsb_android.util;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.MyApplication;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.VersionCodeBean;
import com.banshuibao.bsb_android.model.VersionReqModel;
import com.zx.uploadlibrary.listener.impl.UIProgressListener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by wangpan on 2017/4/26.
 */

public class VersionCodeUtil2 {
    private Context context;
    private ProgressBar progressBar;
    private Dialog dialog;
    private TextView download_status;
    private AlertDialog dialog1;
    MyApplication myApplication;
    private String des;

    public VersionCodeUtil2(Context context) {
        this.context = context;
        myApplication = MyApplication.applicationInstance;
    }

    public void up() {
        //设置contentView
        View contentView = View.inflate(context, R.layout.update_layout, null);
        if (dialog != null && dialog.isShowing()) {
            return;
        }
        if (dialog1 == null) {
            dialog1 = new AlertDialog.Builder(context).setView(contentView).create();
        }
        dialog1.setCanceledOnTouchOutside(false);
        dialog1.setCancelable(false);
        TextView ok = contentView.findViewById(R.id.ok);
        TextView no = contentView.findViewById(R.id.no);
        TextView msg = contentView.findViewById(R.id.msg);
        msg.setText("办税宝有新版本，是否立即更新");
        dialog1.show();
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isO()) {
                    intit_getClick();
                    return;
                }
                ;
                showDownLoadDialog(Constants.APK.APK_ADDRESS + "banshuibao.apk");
                dialog1.dismiss();
                dialog1.cancel();
            }
        });
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
                dialog1.cancel();
            }
        });
    }

    private void showDownLoadDialog(String path) {
        if (dialog == null) {
            View view = LayoutInflater.from(context).inflate(R.layout.dialog_download_progress, null);
            TextView title =  view.findViewById(R.id.title);
            download_status =  view.findViewById(R.id.download_status);
            title.setText("下载中请稍候");
            download_status.setText("正在下载");
            progressBar =  view.findViewById(R.id.progress_bar);
            dialog = new AlertDialog.Builder(context).setView(view).setCancelable(false).create();
        }
        dialog.show();
        download(path);
    }

    /**
     * 安装apk的方法
     */
    void update() {
        //使用隐身跳转
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //版本在7.0以上是不能直接通过uri访问的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            File file = (new File(Environment
                    .getExternalStorageDirectory(), Constants.APK.APK_NAME));
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致 参数3 共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, "com.banshuibao.bsb_android.fileprovider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            //设置类型和数据
            intent.setDataAndType(Uri.fromFile(new File(Environment
                            .getExternalStorageDirectory(), Constants.APK.APK_NAME)),
                    "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }


        //开始跳转
        context.startActivity(intent);
    }

    /**
     * 请求更新apk的方法
     *
     * @param downloadUrl 更新的路径
     */
    public void download(String downloadUrl) {
        HttpUtil.doDownload(downloadUrl, new UIProgressListener() {
            @Override
            public void onUIProgress(long l, long l1, boolean b) {
                if (l1 == 0) return;
                int progress = (int) ((100 * l) / l1);
                progressBar.setProgress(progress);
                download_status.setText("下载进度: " + progress + "%");
            }

            @Override
            public void onUIFinish(long currentBytes, long contentLength, boolean done) {
                super.onUIFinish(currentBytes, contentLength, done);
                dialog.cancel();
            }
        }, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                XToast.showToast(context, "下载失败");
                dialog.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 200) {
                    try {
                        if (FileUtil.saveDownloadFile(response, Environment.getExternalStorageDirectory().getPath() + "/", Constants.APK.APK_NAME))
                            FileUtil.fileScan(context);
                        //设置安装apk的方法
                        update();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        });
    }

    //判断版本更新
    public void getVersionCode() {
        VersionReqModel versionReqModel = new VersionReqModel();
        versionReqModel.setDeviceType(1);//1为安卓 0 为 ios
        HttpUtil.doPost(Constants.Url.VERSION_CODE, versionReqModel, new HttpResponse(context, VersionCodeBean.class) {
            @Override
            public void onResult(Object obj) {
                VersionCodeBean vcb = (VersionCodeBean) obj;
                if (vcb.getData() == null) {
                    return;
                }
                int versionCode = vcb.getData().getUpCode();
                int versionCode2;
                des = vcb.getData().getDescription();
                if (Build.VERSION.SDK_INT >= 19) {
                    try {
                        versionCode2 = context.getPackageManager().getPackageInfo(
                                "com.banshuibao.bsb_android", 0).versionCode;
                        if (versionCode > versionCode2) {
                            up();
                        } else {
                            XToast.showToast(context, "您已是最新版本");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    String packageName = "com.banshuibao.bsb_android";
                    Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    //  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                    intent.setData(Uri.parse("package:" + packageName));
                    context.startActivity(intent);
                }
            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    public void destroy() {
        if (dialog1 != null) {
            dialog1.dismiss();
            dialog1.cancel();
        }
    }


    public boolean isO() {
        if (Build.VERSION.SDK_INT >= 26) {
            boolean b = context.getPackageManager().canRequestPackageInstalls();
            if (b) {
                return true;//安装应用的逻辑(写自己的就可以)
            } else {
                //请求安装未知应用来源的权限
                return false;

            }
        }
        return true;
    }


    private void intit_getClick() {
        if (isAvilible(context, "com.tencent.android.qqdownloader")) {
            // 市场存在
            //    Toast.makeText(context, "ssss", Toast.LENGTH_SHORT).show();
            launchAppDetail(context, "com.banshuibao.bsb_android", "com.tencent.android.qqdownloader");
        } else {
            Uri uri = Uri.parse("http://a.app.qq.com/o/simple.jsp?pkgname=com.banshuibao.bsb_android");
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            context.startActivity(it);
        }
    }

    /**
     * 启动到app详情界面
     *
     * @param appPkg    App的包名
     * @param marketPkg 应用商店包名 ,如果为""则由系统弹出应用商店列表供用户选择,否则调转到目标市场的应用详情界面，某些应用商店可能会失败
     */
    public static void launchAppDetail(Context context, String appPkg, String marketPkg) {
        try {
            if (TextUtils.isEmpty(appPkg))
                return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            if (!TextUtils.isEmpty(marketPkg))
                intent.setPackage(marketPkg);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 判断市场是否存在的方法
    public static boolean isAvilible(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        List<String> pName = new ArrayList<String>();// 用于存储所有已安装程序的包名
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);// 判断pName中是否有目标程序的包名，有TRUE，没有FALSE
    }

}
